import { isToken,wxConcerned,isTokens,collection,cityAll,getCityByLocation,enterPrecontract,getUploadToken} from '@/utils/api.js'
import config from '@/config.js'
import * as qiniu from 'qiniu-js'
export default {
	computed: {
		
	},
	onShow() { 
		
	},
	methods: {
		checkLogin(token){
			if(token == 'undefined' && token == ''){
					return token;
			}
		},
		// 校验token是否有效
		verifyToken(token){
			return new Promise(async(resolve,reject) => { 
				var token = uni.getStorageSync('TOKEN');   //获取缓存token
				if(token != 'undefined' && token != ''){  
					await isToken().then((res) => {    //校验token是否有效  有效200  无效401
						if(res.code == 401){ 
							resolve(401)	  
						}else{
							resolve(200)	
						}
					})  
				}
				if(!token){  
					uni.navigateTo({
						url:'/pages/login/index'
					}) 
					return ;
				}
			}) 
		},
		// 校验token是否有效  无拦截
		verifyTokens(token){
			return new Promise(async(resolve,reject) => { 
				var token = uni.getStorageSync('TOKEN');   //获取缓存token
				if(token != 'undefined' && token != ''){  
					await isTokens().then((res) => {    //校验token是否有效  有效200  无效401
						if(res.code == 401){ 
							resolve(401)	  
						}else{
							resolve(200)	
						}
					})  
				} 
			}) 
		},
		// 立即预约校验
		enterPrecontract(massagistId){
			return new Promise(async(resolve,reject) => { 
				var token = uni.getStorageSync('TOKEN');   //获取缓存token
				if(token != 'undefined' && token != ''){  
					await enterPrecontract({massagistId:massagistId}).then((res) => {    //校验token是否有效  有效200  无效401
						if(res.code == 401){ 
							resolve(401)	  
						}else if(res.code == 8001){ 
							resolve(res)	  
						}else{
							resolve(200)	
						}
					})  
				}
				if(!token){  
					uni.navigateTo({
						url:'/pages/login/index'
					}) 
					return ;
				}
			}) 
		},
		goWechatUrl(){
			// https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN   微信获取用户信息
			// subscribe	用户是否订阅该公众号标识，值为0时，代表此用户没有关注该公众号，拉取不到其余信息。  关注值为1
			//  window.wx.uin = "3930621696" || "0";
			window.location.href="https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzkzMDYyMTY5Ng==&scene=117#wechat_redirect" 
		},
		// 跳转到微信公众号
		// goWechatUrl(){ 
		// 	// 接口判断是否关注公众号
		// 	return new Promise((resolve, reject) => {
		// 		wxConcerned().then(res => { 
		// 			console.log(res);
		// 			alert(res);
		// 			if(res.result=='0'){
		// 				uni.showModal({
		// 					title: '是否关注公众号授权消息订阅功能',
		// 					success(res) {
		// 						if (res.confirm) {
		// 							window.location.href="https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzkzMDYyMTY5Ng==#wechat_redirect" 
		// 						} 
		// 					}
		// 				}) 
		// 			} 
		// 		}).catch(err => { });
		// 	}); 
		// },
		// 小程序订阅消息
		subScribeMsg() {
		  return new Promise((resolve, reject) => {
		    uni.getSetting({
		      withSubscriptions: true,
		      success(res) {
		        console.log('1', res, '订阅信息', res.subscriptionsSetting);
		        if (!res.subscriptionsSetting.mainSwitch) { 
							uni.showModal({
								title: '是否重新授权消息订阅功能',
								success(res) {
									if (res.confirm) {
										uni.openSetting({
												success(res) {
													if (res.subscriptionsSetting) {
														// Toast('开启权限成功')
													}
												},
											 fail() {
												 // Toast('开启权限失败')
											 },
										 })
									 } else if (res.cancel) {
										 // Toast('拒绝开启开启权限')
									 }
								 }
							 }) 
		        } else {
							console.log(config.appInfo.WeChatMiniTemplate[0],"订阅id"); 
							uni.requestSubscribeMessage({
							  tmplIds: [config.appInfo.WeChatMiniTemplate[0], config.appInfo.WeChatMiniTemplate[1],config.appInfo.WeChatMiniTemplate[2],],
							  success(res) {
							    console.log('requestSubscribeMessage 订阅信息', res);  
							    resolve(res) 
							  },
							  fail(errMessage) {
							    reject(errMessage)
							    console.log("订阅消息 失败 ", errMessage);
							  },
							  complete() {}
							})
		        }
		      },
		    })
		  })
		} ,
		isCollect(id){
			return new Promise(async(resolve,reject) => {
				if(!uni.getStorageSync('TOKEN')){
					return uni.navigateTo({
						url:'/pages/login/index'
					})  
				}
				collection({'massagistId':id}).then((res) => {
					if(res.code == '200'){ 
						if(res.result.collection){
							uni.showToast({
								title:'感谢您的收藏，下次可以在我的收藏里找到我～',  //已取消收藏，下次想找到我，可以搜索我的名字～
								icon:'none'
							})
						}else{
							uni.showToast({
								title:'已取消收藏，下次想找到我，可以搜索我的名字～',  //
								icon:'none'
							})
						}
						resolve()	  
					}  
				}) 
			})  
		},
		// 获取所有城市
		getCity(){ 
			return new Promise(async(resolve,reject) => {
				const citys = []
				const columns = []
				cityAll().then((res) => { 
					if(res.code == '200'){ 
						res.result.forEach((item,index)=>{    
							citys.push(item.cityName)
							if(item.id.indexOf(uni.getStorageSync('cityId')) != -1 ){ 
								this.$refs.picker.setIndexs([index],true)  
							}
						})   
						this.columns[0] = citys  
						uni.setStorageSync('cityArr',this.columns)   
						this.columns = uni.getStorageSync('cityArr') 
						resolve()	
					}
				})  
			})  
		},
		// 获取当前城市id
		getCurrentCity(){
			return new Promise(async(resolve,reject) => {
				getCityByLocation({
					"lon":uni.getStorageSync('longitude'),  //经度
					"lat":uni.getStorageSync('latitude'),  //纬度 
				}).then((res) => { 
					if(res.code == '200'){ 
						console.log(res,"当前城市信息"); 
						// alert('获取城市信息')
						if(!uni.getStorageSync('isManual')){
							uni.setStorageSync('cityName',res.result.cityName)
							uni.setStorageSync('cityId',res.result.id) 
						} 
						resolve()	
					}
				})  
			})   
		},
		
		//状态栏 标题栏高度
		menuButton() {
			uni.getSystemInfoSync({
				success: result => {
					this.safeareaHeight = result.screenHeight - result.safeArea.bottom;
				},
			})
			// #ifdef MP-WEIXIN
			let menuButtonObject = uni.getMenuButtonBoundingClientRect(); //获取菜单按钮（右上角胶囊按钮）的布局位置信息。坐标信息以屏幕左上角为原点。
			uni.getSystemInfo({//获取系统信息
				success: res => {
					let navHeight = menuButtonObject.height + (menuButtonObject.top - res.statusBarHeight)*2;//导航栏高度=菜单按钮高度+（菜单按钮与顶部距离-状态栏高度）*2
					this.titleBarHeight = navHeight;  //导航栏的高度
					this.statusBarHeight = res.statusBarHeight;     //状态栏高度
					this.allBarHeight = res.statusBarHeight + navHeight;  //总高度
					console.log(this.titleBarHeight);
				},
				fail(err) {
					console.log(err);
				}
			})
			// #endif
			// #ifdef H5
			this.titleBarHeight = '50';
			this.statusBarHeight = '0';
			this.allBarHeight = '50';
			// #endif
			console.log(this.titleBarHeight,this.statusBarHeight,this.allBarHeight);
		},
		// 获取两个时间毫秒数
		dataMs(firstDate,times){
			//1)将两个日期字符串转化为日期对象
			var startDate = new Date(this.date_ios_format(firstDate));
			// var endDate = new Date();
			//2)计算两个日期相差的毫秒数 
			var endDate = startDate.getTime() + times 
			var msecNum = endDate - new Date().getTime(); 
			return msecNum;
		}, 
		date_ios_format(datestr) {
		    return datestr.replace(/\-/g, "/");
		},
		// 处理图片路径
		initKeyUrl(key) {
			return new Promise((resolve, reject) => {  
				geturl({
					key: key
				}).then(res => {
					resolve(res.result)
				}).catch(err => {
					reject(err)
				});
			});
		},
		// res.result.forEach(async(item,indexs)=>{
		// 	if(item.imgKey!=''){
		// 		item.imgKey = await this.initKeyUrl(item.imgKey)  
		// 	} 
		// }) 
		//处理金额
		conversion(num){
			let str = (num / 100).toFixed(2) + '';
			let intSum = str.substring(0, str.indexOf('.')).replace(/\B(?=(?:\d{3})+$)/g, ',');//取到整数部分
			let dot = str.substring(str.length, str.indexOf('.'));//取到小数部分搜索
			let ret = intSum + dot;
			return ret;
		},
		//处理金额整数
		integer(num){
			let str = (num / 100).toFixed(2) + '';
			let intSum = str.substring(0, str.indexOf('.')).replace(/\B(?=(?:\d{3})+$)/g, ',');//取到整数部分 
			return intSum;
		},
		goBack(){
			uni.navigateBack({
				delta: 1,
				animationType: 'pop-out',
				animationDuration: 200
			})
		}, 
		//base64转换为blob文件流
		parseBlob(base64) { 
			return new Promise((resolve, reject) => { 
				var arr = base64.split(',');
				var mime = arr[0].match(/:(.*?);/)[1];
				var bstr = atob(arr[1]);
				var n = bstr.length;
				var u8arr = new Uint8Array(n);
				for(var i = 0; i < n; i++) {
					u8arr[i] = bstr.charCodeAt(i);
				} 
				var url = URL || webkitURL; 
				resolve(new Blob([u8arr], {type: mime})) 
			})
		},
		//七牛云上传
		uploadQiniu(file) { 
			return new Promise((resolve, reject) => { 
				getUploadToken().then((res) => { 
					var tokencode = res.result
					if (res.code === '200') {
						// 初始化七牛上传策略和配置
						const putPolicy = { }
						const config = {
							useCdnDomain: true, // 是否使用CDN上传加速
							region: qiniu.region.z1
						}
						const filename = 'web_user_' + new Date().getTime() + ('000000' + Math.floor(Math.random() * 999999)).slice(-6) + '.png'; 
						// 创建上传管理对象
						const observable = qiniu.upload(file, filename, tokencode, putPolicy, config)
						observable.subscribe({
							next (res) {
								console.log('进度', res)
							},
							error (err) { 
								reject(err)
								console.log('失败', err) 
							},
							complete (res) {  
								resolve(res)
								console.log('成功', res)  
							}
						})
					} 
				}) 
			})
		},
	}
} 